#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int N=60;
typedef pair<int,int> PII;
int n,m;
int ans;
char v[N][N];
int rex[8]={0,0,1,-1,1,1,-1,-1};
int rey[8]={1,-1,0,0,1,-1,-1,1};
bool vis[N][N];
void bfs1(int x,int y)
{
    ans++;
    queue<PII> q;
    vis[x][y]=true;
    q.push({x,y});
    while(q.size())
    {
        auto qt=q.front();
        int xx=qt.first;
        int yy=qt.second;
        q.pop();
        for(int i=0;i<4;i++)
        {
            int x1=xx+rex[i];
            int y1=yy+rey[i];
            if(x1>=1&&x1<=m&&y1>=1&&y1<=n&&v[x1][y1]=='1'&&!vis[x1][y1]){
                vis[x1][y1]=true;
                q.push({x1,y1});
            }
        }
    }
}
void bfs2(int x,int y)
{
    queue<PII> q;
    vis[x][y]=true;
    q.push({x,y});
    while(q.size())
    {
        auto qt=q.front();
        int xx=qt.first;
        int yy=qt.second;
        q.pop();
        for(int i=0;i<8;i++)
        {
            int x1=xx+rex[i];
            int y1=yy+rey[i];
            if(x1>=0&&x1<=m+1&&y1>=0&&y1<=n+1&&!vis[x1][y1]){
                if(v[x1][y1]=='1'){
                    bfs1(x1,y1);
                }else{
                    vis[x1][y1]=true;
                    q.push({x1,y1});
                }
            }
        }
    }
}
void solve()
{
    ans=0;
    cin >> m >> n;
    for(int i=1;i<=m;i++)
    {
        for(int j=1;j<=n;j++)
        {
            cin >> v[i][j];
        }
    }
    bfs2(0,0);
    cout << ans << endl;
}
int main()
{
    int T;
    cin >> T;
    while(T--)
    {
        memset(vis,false,sizeof vis);
        memset(v,'0',sizeof v);
        solve();
    }
    return 0;
}